from beancount.core import account
from beancount.core.account import Account
from beancount.core.data import Open
from beancount.parser import printer
from datetime import datetime

def create_beancount_account(account_name, account_type, file_path, currency, start_date=None):
    # 检查账户名是否已经包含账户类型前缀
    if not account_name.startswith(f"{account_type}:"):
        # 如果不包含，则添加前缀
        full_account_name = f"{account_type}:{account_name}"
    else:
        # 如果已包含，直接使用原名
        full_account_name = account_name
    
    if start_date is None:
        current_year = datetime.now().year
        start_date = datetime(current_year, 1, 1).date()
    else:
        start_date = datetime.strptime(start_date, "%Y-%m-%d").date()
    
    # 尝试修复账户名称格式问题
    # 移除可能导致问题的空格
    full_account_name = full_account_name.replace(" ", "")
    
    # 确保每个组件都是有效的
    components = full_account_name.split(':')
    for i, component in enumerate(components):
        # 确保每个组件都是有效的标识符
        if not component.isalnum() and not all(c.isalnum() or c == '-' for c in component):
            components[i] = ''.join(c for c in component if c.isalnum() or c == '-')
    
    full_account_name = ':'.join(components)
    
    # 检查账户名是否有效
    if not account.is_valid(full_account_name):
        # 如果仍然无效，尝试使用更简单的名称
        simplified_name = f"{account_type}:{components[-1]}" if len(components) > 1 else full_account_name
        if account.is_valid(simplified_name):
            full_account_name = simplified_name
        else:
            raise ValueError(f"Invalid account name: {full_account_name}")
    
    open_directive = Open(
        date=start_date,
        account=full_account_name,
        currencies=[currency],
        meta=None,
        booking=None
    )
    
    # 将账户指令写入文件
    with open(file_path, 'a', encoding='utf-8') as f:
        f.write(printer.format_entry(open_directive) + '\n')
    
    return open_directive

# 更新主函数示例
if __name__ == "__main__":
    ledger_file = "c:\\code\\acccount\\main.beancount"
    
    # 软件外包公司账户科目
    software_accounts = [
        # 资产账户
        ("ITCompany:Bank", "Assets"),
        ("ITCompany:ProjectReceivable", "Assets"),  # 项目应收款
        ("ITCompany:Equipment", "Assets"),          # 开发设备
        ("ITCompany:OfficeAssets", "Assets"),       # 办公资产
        
        # 负债账户
        ("ITCompany:SalaryPayable", "Liabilities"),    # 应付工资
        ("ITCompany:TaxPayable", "Liabilities"),       # 应付税金
        ("ITCompany:ContractLiability", "Liabilities"), # 合同预收款
        
        # 收入账户
        ("ITCompany:ProjectIncome", "Income"),         # 项目收入
        ("ITCompany:ConsultingIncome", "Income"),      # 咨询收入
        ("ITCompany:MaintenanceIncome", "Income"),     # 维护收入
        
        # 支出账户
        ("ITCompany:DevSalary", "Expenses"),          # 开发人员工资
        ("ITCompany:PMSalary", "Expenses"),           # 项目经理工资
        ("ITCompany:SocialInsurance", "Expenses"),     # 社保费用
        ("ITCompany:ServerCost", "Expenses"),          # 服务器成本
        ("ITCompany:SoftwareLicense", "Expenses"),     # 软件授权费用
        ("ITCompany:Training", "Expenses"),            # 培训费用
        ("ITCompany:Travel", "Expenses"),              # 差旅费
        ("ITCompany:Office", "Expenses"),              # 办公费用
        ("ITCompany:Recruitment", "Expenses")          # 招聘费用
    ]

    try:
        for account_name, account_type in software_accounts:
            open_directive = create_beancount_account(
                account_name=account_name,
                account_type=account_type,
                file_path=ledger_file,
                currency="CNY"
            )
            print(f"✓ 创建账户成功: {account_name}")
            
    except ValueError as e:
        print(f"创建账户错误: {e}")